package com.rcloud.stock.ui.search;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;

import com.rcloud.stock.R;
import com.rcloud.stock.adapter.SearchAnswerAdapter;
import com.rcloud.stock.adapter.SearchHistoryAdapter;
import com.rcloud.stock.database.History;
import com.rcloud.stock.util.BottomScrollView;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import static android.content.ContentValues.TAG;

public class SearchFragment extends Fragment {

    //适配器
    private SearchHistoryAdapter historyAdapter;
    private SearchAnswerAdapter answerAdapter;
    //控件
    private RecyclerView historyRecyclerView;
    private EditText  editText;
    private ImageView searchBtn;
    private SearchViewModel searchViewModel;
    private ProgressBar progressBar;
    private TextView titleView;
    private ImageView backBtn;
    //时间格式化
    private final DateFormat df = new SimpleDateFormat("HH:mm:ss", Locale.CHINA);
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        searchViewModel = new ViewModelProvider(this).get(SearchViewModel.class);
        return inflater.inflate(R.layout.fragment_search, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initAdapter();
        initView(view);
        initListener();
    }

    private void initListener() {
        //异步观察，初始化搜索历史
        searchViewModel.getHistories().observe(getViewLifecycleOwner(),histories -> {
            if (histories!=null){
                historyAdapter.submitList(histories);
            }
        });
        //异步观察，填充搜索栏
        searchViewModel.getPatternLive().observe(getViewLifecycleOwner(),s -> {
            editText.setText(s);
        });
        //异步观察搜索请求
        searchViewModel.getStocks().observe(getViewLifecycleOwner(),stocks -> {
            Log.d(TAG, "initListener: 监听搜索");
            //隐藏加载图标
            progressBar.setVisibility(View.GONE);
            //提交数据，显示搜索结果
            answerAdapter.submitList(stocks);
        });

        searchBtn.setOnClickListener(v -> {
            if (!TextUtils.isEmpty(editText.getText())){
                //保存搜索记录
                searchViewModel.insertHistory(new History(df.format(new Date()),editText.getText().toString()));
                //执行搜索
                searchViewModel.fetchStockWithPattern(editText.getText().toString());
                //切换适配器，显示加载图标,切换标题
                historyRecyclerView.setAdapter(answerAdapter);
                progressBar.setVisibility(View.VISIBLE);
                titleView.setText("搜索结果");
                //使editText失去焦点
                editText.clearFocus();
            }
        });

        editText.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus){
                //切换适配器，切换标题
                historyRecyclerView.setAdapter(historyAdapter);
                titleView.setText("搜索历史");
            }
        });



        //返回事件
        backBtn.setOnClickListener(v -> {
            editText.clearFocus();
            NavController controller = Navigation.findNavController(requireActivity(),R.id.nav_host_fragment);
            controller.navigateUp();
        });
    }

    private void initAdapter() {
        historyAdapter = new SearchHistoryAdapter(searchViewModel);
        answerAdapter = new SearchAnswerAdapter();
    }

    private void initView(View view) {
        //初始化搜索历史
        historyRecyclerView = view.findViewById(R.id.search_history_recycler);
        historyRecyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));
        historyRecyclerView.setAdapter(historyAdapter);

        //搜索相关
        searchBtn = view.findViewById(R.id.searchBtn);
        editText = view.findViewById(R.id.searchEditText);
        progressBar = view.findViewById(R.id.progressBar);
        titleView = view.findViewById(R.id.search_content_title);

        //返回
        backBtn = view.findViewById(R.id.backImageView);
    }
}